<template>
  <div class="cate-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>数据分类管理</h3>
          <el-button type="primary" @click="handleAdd">新增分类</el-button>
        </div>
      </template>

      <el-table :data="cateList" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="分类名称" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        @current-change="handlePageChange"
        :current-page="queryParams.page"
        :page-size="queryParams.limit"
        :total="total"
        layout="total, prev, pager, next"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleClose">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/request'

  interface CateItem {
    id: number
    title: string
    status: number
    create_time?: string
    update_time?: string
  }

  const cateList = ref<CateItem[]>([])
  const loading = ref(false)
  const submitLoading = ref(false)
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const formRef = ref<FormInstance>()
  const total = ref(0)

  const queryParams = reactive({
    page: 1,
    limit: 10,
    keywords: '',
  })

  const formData = reactive({
    id: 0,
    title: '',
    status: 1,
  })

  const rules: FormRules = {
    title: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  }

  // 加载分类列表
  const loadCateList = async () => {
    loading.value = true
    try {
      const response: any = await request({
        url: '/api/contract/cate/list',
        method: 'get',
        params: {
          page: queryParams.page,
          limit: queryParams.limit,
        },
      })

      if (response.code === 0) {
        cateList.value = response.data
        total.value = response.count || 0
      } else {
        ElMessage.error(response.msg || '加载数据失败')
      }
    } catch (error) {
      ElMessage.error('加载数据失败')
    } finally {
      loading.value = false
    }
  }

  // 处理分页变化
  const handlePageChange = (page: number) => {
    queryParams.page = page
    loadCateList()
  }

  // 处理新增
  const handleAdd = () => {
    dialogTitle.value = '新增分类'
    formData.id = 0
    formData.title = ''
    formData.status = 1
    dialogVisible.value = true
  }

  // 处理编辑
  const handleEdit = (row: CateItem) => {
    dialogTitle.value = '编辑分类'
    Object.assign(formData, row)
    dialogVisible.value = true
  }

  // 处理删除
  const handleDelete = async (row: CateItem) => {
    try {
      await ElMessageBox.confirm(`确定要删除"${row.title}"吗？`, '提示', {
        type: 'warning',
      })

      const response: any = await request({
        url: '/api/contract/cate/del',
        method: 'delete',
        data: { id: row.id },
      })

      if (response.code === 0) {
        ElMessage.success('删除成功')
        loadCateList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.response?.data?.msg || '删除失败')
      }
    }
  }

  // 处理提交
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async valid => {
      if (valid) {
        submitLoading.value = true
        try {
          let response: any
          if (formData.id) {
            // 编辑
            response = await request({
              url: '/api/contract/cate/edit',
              method: 'put',
              data: formData,
            })
          } else {
            // 新增
            response = await request({
              url: '/api/contract/cate/add',
              method: 'post',
              data: formData,
            })
          }

          if (response.code === 0) {
            ElMessage.success(formData.id ? '更新成功' : '新增成功')
            dialogVisible.value = false
            loadCateList()
          } else {
            ElMessage.error(response.msg || '操作失败')
          }
        } catch (error) {
          ElMessage.error('操作失败')
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 处理关闭对话框
  const handleClose = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }

  onMounted(() => {
    loadCateList()
  })
</script>

<style scoped>
  .cate-list-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
  }
</style>
